<template>
  <div class="set-range" v-loading="loading">
    <div class="block">
      <div class="title">数据范围</div>
      <div class="row district-row">
        <div class="item">
          <div class="label">省</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.province_list"
              placeholder="选择省份"
              value-key="F_id"
              @change="changeProvinceList"
            >
              <el-option
                v-for="item in accountDistrict.province_list"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="item">
          <div class="label">市</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.city_list"
              placeholder="选择城市"
              value-key="F_id"
              @change="changeCityList"
            >
              <el-option
                v-for="item in accountDistrict.city_list"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="item">
          <div class="label">区（县）</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.county_list"
              placeholder="选择区（县）"
              value-key="F_id"
              @change="changeCountyList"
            >
              <el-option
                v-for="item in accountDistrict.county_list"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="item">
          <div class="label">学段</div>
          <div class="data">
            <el-select
              v-model="newDistrict.stage"
              placeholder="选择学段"
              @change="handleStageChange"
            >
              <el-option
                v-for="item in stageList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="row" v-if="showExamSubjects">
        <div class="item">
          <div class="label">科目</div>
          <div class="data">
            <div class="subject-list">
              <div
                v-for="(item, index) in subjectList"
                :key="index"
                class="subject-item"
                :class="{ active: isSubjectSelected(item) }"
                @click="toggleSubject(item)"
              >
                {{ item.name }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex';
import { subjectList } from '@/utils/maps';

export default {
  name: 'setRange',
  props: {
    type: Number,
    checkedRoleList: {
      type: Array,
      default: () => []
    }
  },
  components: {},
  data() {
    return {
      loading: false,
      accountDistrict: {
        province_list: [],
        city_list: [],
        county_list: [],
        level: 1,
        stage: null
      },
      newDistrict: {
        province_list: [],
        city_list: [],
        county_list: [],
        level: 1,
        subject_list: [],
        stage: null
      },
      level: 1,
      options: {},
      subjectList: subjectList,
      stageList: [
        { id: 1, name: '小学' },
        { id: 2, name: '初中' },
        { id: 3, name: '高中' }
      ]
    };
  },
  async mounted() {
  },
  watch: {
    async type() {
      await this.getAccountDistrict();
      this.getNewDistrict();
      // this.setWachter();
    },
    'accountDistrict.province_list': {
      async handler(v) {
        if (v.length === 1) {
          if (!this.accountDistrict.city_list.length) {
            this.accountDistrict.city_list = await this.getDistricts(v[0].F_id);
          }
        }
      },
    },
    'accountDistrict.city_list': {
      async handler(v) {
        if (v.length === 1) {
          if (!this.accountDistrict.county_list.length) {
            this.accountDistrict.county_list = await this.getDistricts(
              v[0].F_id
            );
          }
        }
      },
    },
  },
  computed: {
    ...mapState('user', ['userInfo']),
    ...mapGetters('user', ['isSuperAdmin', 'userPermission']),
    showExamSubjects() {
      // 根据角色判断是否显示选考科目
      return this.checkedRoleList.some(role => 
        ['教师', '学生'].includes(role.F_role_name)
      );
    }
  },
  methods: {
    async getAccountDistrict() {
      // 获取最大数据范围
      if (!this.isSuperAdmin) {
        this.accountDistrict = JSON.parse(JSON.stringify(this.userPermission));
      } else {
        // 是超管，给它最大数据范围就好了
        this.accountDistrict.level = 1;
        this.accountDistrict.province_list = await this.getDistricts(0);
      }
    },
    getNewDistrict() {
      const levelNameList = [
        'province_list',
        'city_list',
        'county_list',
      ];
      const editUserInfo = JSON.parse(sessionStorage.getItem('edit_system_user_info'));
      if (editUserInfo) {
        // 当前是编辑页面
        // 优先使用 F_district，如果没有则使用 F_describe（兼容旧数据）
        const districtStr = editUserInfo.F_district || editUserInfo.F_describe || '';
        if (!districtStr) {
          // 如果区域信息为空，初始化所有列表为空
          this.newDistrict = {
            province_list: [],
            city_list: [],
            county_list: [],
            subject_list: [],
            stage: null,
            level: 0
          };
          return;
        }
        const userRange = JSON.parse(districtStr);
        for (let [k, v] of Object.entries(userRange)) {
          if (k !== 'level' && k !== 'stage' && !Array.isArray(v)) {
            userRange[k] = [];
          }
        }
        // 确保stage字段存在且为数字类型
        if (userRange.stage === undefined || userRange.stage === null) {
          userRange.stage = null;
        } else {
          userRange.stage = Number(userRange.stage);
        }
        this.newDistrict = userRange;

        // 在省市区学校这前4个层级,又需要把newDistrict的这些列表复制给accountDistrict
        for (
          let i = this.accountDistrict.level;
          i < this.newDistrict.level;
          i++
        ) {
          this.accountDistrict[levelNameList[i]] = JSON.parse(
            JSON.stringify(this.newDistrict[levelNameList[i]])
          );
        }
      } else {
        // 添加用户时, 初始化所有列表为空
        this.newDistrict = {
          province_list: [],
          city_list: [],
          county_list: [],
          subject_list: [],
          stage: null,
          level: 0
        };
      }
    },
    async getDistricts(areaId) {
      this.loading = true;
      const { F_districts } = await this.$api.getDistricts2({
        F_parent_id: areaId,
      });
      this.loading = false;
      return F_districts || [];
    },
    async changeProvinceList(val) {
      if (val.length === 0) this.newDistrict.level = 0;
      else this.newDistrict.level = 1;
      this.newDistrict.city_list = [];
      this.newDistrict.county_list = [];
      this.accountDistrict.city_list = [];
      this.accountDistrict.county_list = [];
      if (val.length === 1) {
        this.accountDistrict.city_list = await this.getDistricts(val[0].F_id);
      }
    },
    async changeCityList(val) {
      if (val.length === 0) this.newDistrict.level = 1;
      else this.newDistrict.level = 2;
      this.newDistrict.county_list = [];
      this.accountDistrict.county_list = [];
      if (val.length === 1) {
        this.accountDistrict.county_list = await this.getDistricts(val[0].F_id);
      }
    },
    async changeCountyList(val) {
      if (val.length === 0) this.newDistrict.level = 2;
      else this.newDistrict.level = 3;
      this.newDistrict.school_list = [];
      this.accountDistrict.school_list = [];
    },
    // 对某一级的多选项进行了操作，则清空其后面所有级别的可选列表、已选列表
    async resetBehindLevel() {
      console.log('reset');
      const list = [
        'province_list', // 0
        'city_list', // 1
        'county_list', // 2
        // 'school_list', // 3
      ];
      console.log(this.newDistrict.level);
      for (let i = this.newDistrict.level; i < list.length; i++) {
        // 清空后面所有层级的选中项和可选项
        this.newDistrict[list[i]] = [];
        this.accountDistrict[list[i]] = [];
      }
    },
    isSubjectSelected(subject) {
      return this.newDistrict.subject_list.includes(subject.id);
    },
    toggleSubject(subject) {
      const index = this.newDistrict.subject_list.indexOf(subject.id);
      if (index === -1) {
        this.newDistrict.subject_list.push(subject.id);
      } else {
        this.newDistrict.subject_list.splice(index, 1);
      }
    },
    handleStageChange(val) {
      this.newDistrict.stage = val;
      this.$emit('stage-change', val);
    },
  },
};
</script>

<style lang="less" scoped>
.block {
  margin: 20px 0;
  .title {
    display: flex;
    align-items: center;
    font-size: 20px;
    font-weight: bold;
    padding: 10px 0 20px;
    &:before {
      content: '';
      display: inline-block;
      margin-right: 10px;
      width: 8px;
      height: 24px;
      background-color: #009cff;
    }
  }
  .row {
    display: flex;
    margin-bottom: 15px;
    .item {
      padding-right: 40px;
      .label {
        font-weight: bold;
        padding-bottom: 10px;
        i {
          color: #ff1900;
        }
      }
    }
  }
  .district-row {
    .item {
      width: 300px;
      .el-select {
        width: 100%;
      }
    }
  }
  .school-info-row {
    .item {
      width: 200px;
    }
  }
}

.subject-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  
  .subject-item {
    padding: 8px 16px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
      color: #409eff;
    }
    
    &.active {
      background-color: #409eff;
      color: #fff;
      border-color: #409eff;
    }
  }
}
</style>
